# coding: utf-8

import copy

from flask import request, jsonify
from flask_restful import Api, Resource

from app.op.models import User, GameExchangeReform
from app.relationship.models import InviteLog
from .game_schemas import (
    game_user_schema, add_friend_schema, exchange_reform_schema
)
from .utils import generate_game_sign

api = Api()


@api.resource('/game/getuserinfo')
class GameUserInfoResource(Resource):
    """
    add by zhouhl 2018-05-28
    斗地主获取用户信息接口
    """

    def get(self):
        uid = request.args.get('uid', None)
        if not uid:
            return jsonify({'result': 1, 'msg': '该用户不存在'})

        user = User.get_by_id(uid)
        if not user:
            return jsonify({'result': 1, 'msg': '该用户不存在'})

        user_info = game_user_schema.dump(user)[0]
        friends = list(user.followers) + list(user.followed)
        friend_uids = [i.id for i in friends]
        user_info['friend_uids'] = friend_uids
        user_info['result'] = 0
        user_info['msg'] = '成功'
        resp = jsonify(user_info)
        return resp


@api.resource('/game/add_friend')
class AddFriendResource(Resource):
    """
    add by zhouhl 2018-05-28
    斗地主添加好友接口
    """

    def post(self):
        data, errors = add_friend_schema.load(request.get_json())
        if errors:
            return jsonify({'result': 1, 'msg': '数据错误'})

        # add by zhouhl 2018-07-24 判断好友关系是否已存在
        tmp_log = InviteLog.get_by_args(
            follower_id=data['uid'],
            followed_id=data['dstuid'],
        )
        if tmp_log:
            tmp_log.pass_invite()
            return jsonify({'result': 0, 'msg': '对方已是您的好友'})

        # 添加好友关系
        tmp_log = InviteLog.invite_friend(
            follower_id=data['uid'],
            followed_id=data['dstuid'],
        )
        tmp_log.pass_invite()

        return jsonify({'result': 0, 'msg': '成功'})


@api.resource('/game/exchange_reform')
class ExchangeReformResource(Resource):
    """
    add by zhouhl 2018-05-28
    斗地主兑换通知接口
    """

    def post(self):
        data, errors = exchange_reform_schema.load(request.get_json())
        if errors:
            return jsonify({'result': 1, 'msg': '数据错误'})

        # sign校验
        json_data = copy.deepcopy(request.get_json())
        post_sign = json_data['sign']
        del(json_data['sign'])

        tmp_sign = generate_game_sign(json_data)
        if post_sign != tmp_sign:
            return jsonify({'result': 1, 'msg': '数据签名错误'})

        tmp_record = GameExchangeReform.get_by_args(rid=data['rid'])
        if tmp_record:
            return jsonify({'result': 1, 'msg': '该兑换记录已存在'})

        remote_addr = request.remote_addr
        GameExchangeReform.create(
            remote_addr=remote_addr,
            **data
        )
        return jsonify({'result': 0, 'msg': '成功'})


